package cn.tangsihai.hrm.userdetails;

import cn.tangsihai.hrm.constant.Constants;
import cn.tangsihai.hrm.domain.Login;
import cn.tangsihai.hrm.domain.Permission;
import cn.tangsihai.hrm.mapper.PermissionMapper;
import cn.tangsihai.hrm.service.ILoginService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用来进行身份验证，将要验证的对象重新封装成一个UserDetails
 * 调用AuthenticationManager接口来进行身份验证
 */
@Service
public class JDBCUserDetailService implements UserDetailsService{
    @Autowired
    private ILoginService loginService;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);
        // 根据用户id查询权限
        List<Permission> permissions = null;
        if (login != null){
            permissions = permissionMapper.selectPermissionsByUserId(login.getId());
        }
        // 把用户和权限封装成UserDeatils返回
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if(!permissions.isEmpty()){
            grantedAuthorities = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn()) ).collect(Collectors.toList());
        }

        if (login.getType() == Constants.Login.TYPE_BACKGROUND){
            // 将登录用户的信息存入token中，为了在其他地方使用
            HashMap<String , String> map = new HashMap<>();
            map.put("username", login.getUsername());
            map.put("tenantId", login.getTenantId().toString());
            map.put("tenantName", login.getTenantName());
            map.put("userId", login.getId().toString());
            // 将数据转化为json格式
            String loginByDB = JSON.toJSONString(map);
            // 将数据存入token中
            return new User(loginByDB,
                    login.getPassword(),
                    login.getEnabled(),
                    login.getAccountNonExpired(),
                    login.getCredentialsNonExpired(),
                    login.getAccountNonLocked(),
                    grantedAuthorities);
        }
        return new User(login.getUsername(),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                grantedAuthorities);
    }
}



